<!DOCTYPE html><html lang="zh"><head><meta charset="UTF-8"><script async src="https://www.googletagmanager.com/gtag/js?id=G-MP1THLPZFC"></script><script>function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag("js",new Date),gtag("config","G-MP1THLPZFC")</script><script>var _hmt=_hmt||[];!function(){var e=document.createElement("script");e.src="https://hm.baidu.com/hm.js?956b14594152e1b71ce14695a71235d5";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)}()</script><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1"><meta http-equiv="X-UA-Compatible" content="ie=edge"><meta name="author" content="CS_GUIDER"><meta name="subtitle" content="If not now, when? If not me, who?"><meta name="description" content="欢迎来到我的CS_GUIDER博客！这里提供了全面、实用和最新的Java编程信息。你可以找到Java算法、项目、博客、数据库、Linux系统的教程和笔记。我致力于为您提供Java编程的实用指南和资源，包括Java框架、JVM和Git等。无论您是初学者还是经验丰富的开发人员，都可以从中获益。谢谢您的光临！"><meta name="keywords" content="Java,算法,项目,博客,数据库,Linux,框架,JVM,Git,编程,开发,教程"><title>Educoder | CS_GUIDER&#39;S Blog</title><link rel="icon" href="/favicon.ico"><link rel="stylesheet" href="/css/main.css"><link rel="stylesheet" href="/lib/nprogress/nprogress.css"><script src="/lib/jquery.min.js"></script><script src="/lib/iconify-icon.min.js"></script><script src="https://cdn.tailwindcss.com?plugins=typography"></script><script>tailwind.config={darkMode:"class"}</script><script src="/lib/nprogress/nprogress.js"></script><script>$(document).ready(()=>{NProgress.configure({showSpinner:!1}),NProgress.start(),$("#nprogress .bar").css({background:"#de7441"}),$("#nprogress .peg").css({"box-shadow":"0 0 2px #de7441, 0 0 4px #de7441"}),$("#nprogress .spinner-icon").css({"border-top-color":"#de7441","border-left-color":"#de7441"}),setTimeout((function(){NProgress.done(),$(".fade").removeClass("out")}),800)})</script><script>!function(){const e=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,t=localStorage.getItem("hexo-color-scheme")||"auto";("dark"===t||e&&"light"!==t)&&document.documentElement.classList.toggle("dark",!0);document.documentElement.classList.contains("dark")}(),$(document).ready((function(){const e=window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches,t=document.documentElement.classList.contains("dark");function o(){const e=document.documentElement.classList.contains("dark"),t=document.querySelector("iframe.giscus-frame");t&&t.contentWindow.postMessage({giscus:{setConfig:{theme:e?"dark":"light"}}},"https://giscus.app")}function n(){let t=document.documentElement.classList.contains("dark");localStorage.getItem("hexo-color-scheme");t=!t,document.documentElement.classList.toggle("dark",t),$("#theme-icon").attr("icon",t?"ri:moon-line":"ri:sun-line"),e===t?localStorage.setItem("hexo-color-scheme","auto"):localStorage.setItem("hexo-color-scheme",t?"dark":"light"),o()}$("#theme-icon").attr("icon",t?"ri:moon-line":"ri:sun-line"),window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",e=>{"auto"===(localStorage.getItem("hexo-color-scheme")||"auto")&&(document.documentElement.classList.toggle("dark",e.matches),$("#theme-icon").attr("icon",e.matches?"ri:moon-line":"ri:sun-line"),o())}),$("#toggle-dark").click(e=>{if(!(document.startViewTransition&&!window.matchMedia("(prefers-reduced-motion: reduce)").matches))return void n();const t=e.clientX,o=e.clientY,c=Math.hypot(Math.max(t,innerWidth-t),Math.max(o,innerHeight-o));document.startViewTransition(async()=>{n()}).ready.then(()=>{const e=document.documentElement.classList.contains("dark"),n=[`circle(0px at ${t}px ${o}px)`,`circle(${c}px at ${t}px ${o}px)`];document.documentElement.animate({clipPath:e?[...n].reverse():n},{duration:400,easing:"ease-out",pseudoElement:e?"::view-transition-old(root)":"::view-transition-new(root)"})})})}))</script><meta name="generator" content="Hexo 5.4.2"></head><body class="font-sans bg-white dark:bg-zinc-900 text-gray-700 dark:text-gray-200 relative"><header class="fixed w-full px-5 py-1 z-10 backdrop-blur-xl backdrop-saturate-150 border-b border-black/5"><div class="max-auto"><nav class="flex items-center text-base"><a href="/" class="group"><h2 class="font-medium tracking-tighterp text-l p-2"><img class="w-5 mr-2 inline-block transition-transform group-hover:rotate-[30deg]" id="logo" src="/img/logo.svg" alt="CS_GUIDER'S Blog"> CS_GUIDER&#39;S Blog</h2></a><div id="header-title" class="opacity-0 md:ml-2 md:mt-[0.1rem] text-xs font-medium whitespace-nowrap overflow-hidden overflow-ellipsis">Educoder</div><div class="flex-1"></div><div class="flex items-center gap-3"><a class="hidden sm:flex" href="/">Home</a> <a class="hidden sm:flex" href="/archives">Archives</a> <a class="hidden sm:flex" href="/category">Categories</a> <a class="hidden sm:flex" href="/tag">Tags</a> <a class="w-5 h-5 hidden sm:flex" title="Github" target="_blank" rel="noopener" href="https://github.com/wl2o2o"><iconify-icon width="20" icon="ri:github-line"></iconify-icon></a><a class="w-5 h-5 hidden sm:flex" title="Github" href="rss2.xml"><iconify-icon width="20" icon="ri:rss-line"></iconify-icon></a><a class="w-5 h-5" title="toggle theme" id="toggle-dark"><iconify-icon width="20" icon="" id="theme-icon"></iconify-icon></a></div><div class="flex items-center justify-center gap-3 ml-3 sm:hidden"><span class="w-5 h-5" aria-hidden="true" role="img" id="open-menu"><iconify-icon width="20" icon="carbon:menu"></iconify-icon></span><span class="w-5 h-5 hidden" aria-hidden="true" role="img" id="close-menu"><iconify-icon width="20" icon="carbon:close"></iconify-icon></span></div></nav></div></header><div id="menu-panel" class="h-0 overflow-hidden sm:hidden fixed left-0 right-0 top-12 bottom-0 z-10"><div id="menu-content" class="relative z-20 bg-white/80 px-6 sm:px-8 py-2 backdrop-blur-xl -translate-y-full transition-transform duration-300"><ul class="nav flex flex-col sm:flex-row text-sm font-medium"><li class="nav-portfolio sm:mx-2 border-b sm:border-0 border-black/5 last:border-0 hover:text-main"><a href="/" class="flex h-12 sm:h-auto items-center">Home</a></li><li class="nav-portfolio sm:mx-2 border-b sm:border-0 border-black/5 last:border-0 hover:text-main"><a href="/archives" class="flex h-12 sm:h-auto items-center">Archives</a></li><li class="nav-portfolio sm:mx-2 border-b sm:border-0 border-black/5 last:border-0 hover:text-main"><a href="/category" class="flex h-12 sm:h-auto items-center">Categories</a></li><li class="nav-portfolio sm:mx-2 border-b sm:border-0 border-black/5 last:border-0 hover:text-main"><a href="/tag" class="flex h-12 sm:h-auto items-center">Tags</a></li></ul></div><div class="mask bg-black/20 absolute inset-0"></div></div><main class="pt-14"><link rel="stylesheet" href="/lib/fancybox/fancybox.min.css"><link rel="stylesheet" href="/lib/tocbot/tocbot.min.css"><nav class="post-toc toc text-sm w-48 relative top-32 right-0 opacity-70 hidden lg:block" style="position:fixed!important"></nav><section class="px-6 max-w-prose mx-auto md:px-0"><header class="overflow-hidden pt-6 pb-6 md:pt-12"><div class="pt-4 md:pt-6"><h1 id="article-title" class="text-[2rem] font-bold leading-snug mb-4 md:mb-6 md:text-[2.6rem]">Educoder</h1><div><section class="flex items-center gap-3 text-sm"><span class="flex items-center gap-1"><iconify-icon width="18" icon="carbon-calendar"></iconify-icon><time>2025-09-17</time> </span><span class="text-gray-400">·</span> <span class="flex items-center gap-1"><iconify-icon width="18" icon="ic:round-access-alarm"></iconify-icon><span>17 min</span> </span><span class="text-gray-400">·</span> <span class="flex items-center gap-1"><iconify-icon width="18" icon="icon-park-outline:font-search"></iconify-icon><span>4.2k words</span> </span><span class="text-gray-400">·</span> <span class="flex items-center gap-1"><iconify-icon width="16" icon="icon-park-outline:box" class="mr-2"></iconify-icon><a class="article-category-link" href="/categories/Java-notes/">Java notes</a></span></section></div></div></header><article class="post-content prose m-auto slide-enter-content dark:prose-invert"><ul><li><em>写在前面：</em></li></ul><p>​ 【免责声明：】本笔记发表在hexo博客只便于个人学习使用，若涉及到版权，请联系个人，谢谢！</p><h1 id="educoder头歌Java笔记"><a href="#educoder头歌Java笔记" class="headerlink" title="educoder头歌Java笔记"></a>educoder头歌Java笔记</h1><h2 id="Coding中遇到的问题合集："><a href="#Coding中遇到的问题合集：" class="headerlink" title="Coding中遇到的问题合集："></a><em>Coding中遇到的问题合集：</em></h2><p>““.equals(name) 和name.equals(““) 的区别：</p><p>​ 两个都是比较“”的地址和name的地址是否指向同一个地址，即判断name是否为“”；建议用前者，因为name可能是null，此时name.equals(“”)就会报错，而前者则会避免这个问题</p><p>避免了抛出空指针异常NullPointerException。</p><p>leetcode回文数：</p><ul><li>(s.charAt(i)).get(map) &amp;&amp; map.get(s.charAt(i))，问题同上；出现了抛出空指针异常的问题，使用前者后，测试通过。</li><li>遇到了char与string的类型不匹配的情况，不可强制转换，最后利用string类的replace方法替换字符串，得到了解决。</li></ul><p>​</p><h2 id="对象的构造方法实例"><a href="#对象的构造方法实例" class="headerlink" title="对象的构造方法实例"></a>对象的构造方法实例</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.Scanner;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Test</span> &#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">		<span class="type">Scanner</span> <span class="variable">sc</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line">		<span class="type">String</span> <span class="variable">name</span> <span class="operator">=</span> sc.next();</span><br><span class="line">		<span class="type">String</span> <span class="variable">sex</span> <span class="operator">=</span> sc.next();</span><br><span class="line">		<span class="comment">/****** Begin ******/</span></span><br><span class="line">		<span class="comment">//分别使用两种构造器来创建Person对象  </span></span><br><span class="line">		Person a=<span class="keyword">new</span> <span class="title class_">Person</span>();</span><br><span class="line">		Person b=<span class="keyword">new</span> <span class="title class_">Person</span>(name,sex);</span><br><span class="line">		<span class="comment">/****** End ******/</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//创建Person对象，并创建两种构造方法</span></span><br><span class="line"><span class="comment">/****** Begin ******/</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Person</span>&#123;																	<span class="keyword">class</span> <span class="title class_">swap</span>&#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="title function_">Person</span><span class="params">()</span>&#123;																<span class="keyword">public</span> <span class="title function_">swap</span><span class="params">(<span class="type">int</span> a,<span class="type">int</span> b,<span class="type">int</span> c)</span>&#123;</span><br><span class="line">		System.out.println(<span class="string">&quot;一个人被创建了&quot;</span>);							c=a;a=b;b=c;</span><br><span class="line"></span><br><span class="line">​	&#125;</span><br><span class="line">​	<span class="keyword">public</span> <span class="title function_">Person</span><span class="params">(String name,String sex)</span>&#123;</span><br><span class="line">​		System.out.println(<span class="string">&quot;姓名：&quot;</span>+name+<span class="string">&quot;，性别：&quot;</span>+sex+<span class="string">&quot;，被创建了&quot;</span>);</span><br><span class="line">​	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/****** End ******/</span></span><br></pre></td></tr></table></figure><p>千万注意！！！！！<br>变量名字一定看清楚，上面的代码中，误将name写成了neme!!!!!</p><p><img src="C:\Users\WLei224\AppData\Roaming\Typora\typora-user-images\image-20220617145157883.png" alt="image-20220617145157883"></p><p><code>JAVA</code>中<code>变量</code>的命名和前面第一章所学的<code>标识符</code>命名规则是一样的，不过还是有一些不同，总结下来规则与规范一共有六点：</p><ol><li><p>由字母，下划线，美元符号（$），数字组成，但第一个字符不能是数字。</p></li><li><p>如果变量名是复合型的那么我们采用驼峰式，或者蛇形式的方式。<br>驼峰式：<code>teaCup</code>（表示茶杯的意思），<code>stuAge</code>（学生年龄）<br>蛇形式：<code>tea_cup</code>，<code>stu_age</code></p></li><li><p>如果是单个单词就全小写就行了。</p></li><li><p>千万不要用中文拼音来表达：例如学生年龄：<code>xueShengNianling</code>。</p></li><li><p>在一个方法中变量名不能重复。</p></li><li><p>变量一定要给自己一个确定的类型。</p><h2 id="JAVA中的数据类型"><a href="#JAVA中的数据类型" class="headerlink" title="JAVA中的数据类型"></a>JAVA中的数据类型</h2><p><code>Java</code>基本类型共有八种，基本类型可以分为三类，字符类型<code>char</code>，布尔类型<code>boolean</code>以及数值类型<code>byte、short、int、long、float、double</code>。数值类型又可以分为整数类型<code>byte、short、int、long</code>和浮点数类型<code>float、double</code>。</p><p><code>基本类型不包括String</code></p><h2 id="java类型转换"><a href="#java类型转换" class="headerlink" title="java类型转换"></a>java类型转换</h2><p><img src="C:\Users\WLei224\AppData\Roaming\Typora\typora-user-images\image-20220617152252543.png" alt="image-20220617152252543"></p></li></ol><p>强制类型转换就是将：<strong>表数范围大的数向表数范围小的进行转换</strong>。</p><h2><a href="#" class="headerlink"></a><img src="C:\Users\WLei224\AppData\Roaming\Typora\typora-user-images\image-20220617152333029.png" alt="image-20220617152333029"></h2><h2 id="怎么使用Scanner"><a href="#怎么使用Scanner" class="headerlink" title="怎么使用Scanner"></a>怎么使用Scanner</h2><p>​ 第一种方法：</p><ol><li><p>在类的声明之前，引入扫描仪（<code>Scanner</code>）：</p><p><code>import java.util.Scanner;</code></p></li><li><p>在方法中创建一个扫描仪</p><p><code>Scanner input = new Scanner(System.in);</code></p><p>第二种方法：</p><p>引入并创建扫描器：<code>java.util.Scanner s = new java.util.Scanner(System.in);</code></p></li><li><p>通过扫描仪获取从键盘输入的数据</p><p><code>int i = input.nextInt();</code></p><p><code>String s = input.next();</code></p><h4 id="三目运算符之判断是否闰年？"><a href="#三目运算符之判断是否闰年？" class="headerlink" title="三目运算符之判断是否闰年？"></a>三目运算符之判断是否闰年？</h4></li></ol><p>result=(year%400==0 || year%4==0 &amp;&amp; year%100!=0)? true:false;</p><p>​ System.out.println(year + “年是否为闰年:” + result);</p><h4 id="运算符优先级别排序正确的是"><a href="#运算符优先级别排序正确的是" class="headerlink" title="运算符优先级别排序正确的是()"></a>运算符优先级别排序正确的是()</h4><p>A、 由高向低分别是:()、 ! 、算术运算符、关系运算符、逻辑运算符、赋值 运算符;</p><h2 id="循环综合练习："><a href="#循环综合练习：" class="headerlink" title="循环综合练习："></a>循环综合练习：</h2><p><strong>Java中的两种循环：</strong></p><p>在 Java 语言中，用于循环的语句有两个，一个是 for 循环，一个是 while 循环。而 for 循环其实还有两种实现方法，对于初学者来说，或许仅知道一般的 for 循环，即：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(初始化条件; 限制条件; 迭代语句) &#123;</span><br><span class="line">    <span class="comment">// 循环体</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>而不太了解高级的 for 循环，即：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(变量类型 变量名 : 集合) &#123;</span><br><span class="line">    <span class="comment">// 循环体</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在本文中，咱们就一起来了解了解这两种 for 循环的使用方法以及区别。<br><strong>demo示例：</strong></p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.Arrays;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> 维C果糖</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@create</span> 2017-03-31-上午9:30</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ForDemo</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="type">int</span>[] arr = <span class="keyword">new</span> <span class="title class_">int</span>[]&#123;<span class="number">2</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">5</span>, <span class="number">11</span>, <span class="number">20</span>&#125;;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;第一种 for 循环方法：&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">            System.out.print(arr[i] + <span class="string">&quot; &quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;高级的 for 循环方法：&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> i : arr)&#123;</span><br><span class="line">            System.out.print(i + <span class="string">&quot; &quot;</span>);</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;用 Arrays 的 toString() 方法打印数组：&quot;</span>);</span><br><span class="line"></span><br><span class="line">        System.out.println(Arrays.toString(arr));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p><strong>运行结果：</strong></p><p><img src="https://img-blog.csdn.net/20170331095210507?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzUyNDY2MjA=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="for"></p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line">ATM经典案例：</span><br><span class="line"></span><br><span class="line"><span class="keyword">package</span> step4;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Scanner;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ForPractice4</span> &#123;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line"></span><br><span class="line">​    <span class="comment">/*****start*****/</span></span><br><span class="line"></span><br><span class="line">​    <span class="type">Scanner</span> <span class="variable">input</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);     </span><br><span class="line"></span><br><span class="line">   </span><br><span class="line"></span><br><span class="line">​    System.out.println(<span class="string">&quot;欢迎使用中国人民银行ATM取款机&quot;</span>);     <span class="comment">//在循环体外，只输出一次  </span></span><br><span class="line"></span><br><span class="line">​    </span><br><span class="line"></span><br><span class="line">​    <span class="type">int</span> <span class="variable">capital</span> <span class="operator">=</span> <span class="number">1000</span>;   <span class="comment">//总资金  </span></span><br><span class="line"></span><br><span class="line">​    </span><br><span class="line"></span><br><span class="line">​    <span class="keyword">while</span>(<span class="literal">true</span>) &#123;                    <span class="comment">//循环体设为true，无限循环</span></span><br><span class="line"></span><br><span class="line">​      System.out.println(<span class="string">&quot;输入取款金额：&quot;</span>);     <span class="comment">//循环外层控制“输入金额”</span></span><br><span class="line"></span><br><span class="line">​      <span class="type">int</span> <span class="variable">a</span> <span class="operator">=</span> input.nextInt();                  <span class="comment">//准备接收输入数据</span></span><br><span class="line"></span><br><span class="line">​    </span><br><span class="line"></span><br><span class="line">​      <span class="keyword">if</span>(a &gt; capital) &#123;                        <span class="comment">//执行判断语句，如果输出金额大于总金额，则返回返回外层循环</span></span><br><span class="line"></span><br><span class="line">​        System.out.println(<span class="string">&quot;目前余额：&quot;</span>+capital+<span class="string">&quot;无法满足您的取款需求！&quot;</span>);   </span><br><span class="line"></span><br><span class="line">​        <span class="keyword">continue</span>;                          <span class="comment">//返回外层循环</span></span><br><span class="line"></span><br><span class="line">​        </span><br><span class="line"></span><br><span class="line">​      &#125;<span class="keyword">else</span> &#123;                           <span class="comment">//如果“输入金额”小于capital，则，分支判断开始</span></span><br><span class="line"></span><br><span class="line">​          capital = capital - a;</span><br><span class="line"></span><br><span class="line">​          </span><br><span class="line"></span><br><span class="line">​          System.out.println(<span class="string">&quot;剩余金额：&quot;</span>+capital+<span class="string">&quot;，是否继续（&#x27;1&#x27;：结束，&#x27;2&#x27;：继续）：&quot;</span>);</span><br><span class="line"></span><br><span class="line">​            <span class="comment">//资金等于总资金 - 取款额度</span></span><br><span class="line"></span><br><span class="line">​          </span><br><span class="line"></span><br><span class="line">​          <span class="type">int</span> <span class="variable">change</span> <span class="operator">=</span> input.nextInt();      <span class="comment">//控制输入“1”，“2”，判断是否结束程序</span></span><br><span class="line"></span><br><span class="line">​          <span class="keyword">if</span> (change == <span class="number">1</span>) &#123;</span><br><span class="line"></span><br><span class="line">​            System.out.println(<span class="string">&quot;取款结束！&quot;</span>);    <span class="comment">//如果为1，程序终止</span></span><br><span class="line"></span><br><span class="line">​            <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">​            </span><br><span class="line"></span><br><span class="line">​          &#125;<span class="keyword">else</span> &#123;                         <span class="comment">//如果为其他，则返回外层循环</span></span><br><span class="line"></span><br><span class="line">​            <span class="keyword">continue</span>;</span><br><span class="line"></span><br><span class="line">​          &#125;</span><br><span class="line"></span><br><span class="line">​      &#125;</span><br><span class="line"></span><br><span class="line">​    </span><br><span class="line"></span><br><span class="line">​    &#125;</span><br><span class="line"></span><br><span class="line">​    <span class="comment">/*****end*****/</span></span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h2 id="第1关：将给定的整数进行由小至大排序"><a href="#第1关：将给定的整数进行由小至大排序" class="headerlink" title="第1关：将给定的整数进行由小至大排序"></a>第1关：将给定的整数进行由小至大排序</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"> int a;</span><br><span class="line"></span><br><span class="line">​    if(x&gt;y)&#123;</span><br><span class="line"></span><br><span class="line">​      a=y;</span><br><span class="line"></span><br><span class="line">​      y=x;</span><br><span class="line"></span><br><span class="line">​      x=a;</span><br><span class="line"></span><br><span class="line">​    &#125;</span><br><span class="line"></span><br><span class="line">​    </span><br><span class="line"></span><br><span class="line">​    if(x&gt;z)&#123;</span><br><span class="line"></span><br><span class="line">​      a=x;</span><br><span class="line"></span><br><span class="line">​      x=z;</span><br><span class="line"></span><br><span class="line">​      z=a;</span><br><span class="line"></span><br><span class="line">​    &#125;</span><br><span class="line"></span><br><span class="line">​    if(y&gt;z)&#123;</span><br><span class="line"></span><br><span class="line">​      a=z;</span><br><span class="line"></span><br><span class="line">​      z=y;</span><br><span class="line"></span><br><span class="line">​      y=a;</span><br><span class="line"></span><br><span class="line">​    &#125;</span><br></pre></td></tr></table></figure><h2 id="关于质数：（难度级别：⭐⭐⭐）"><a href="#关于质数：（难度级别：⭐⭐⭐）" class="headerlink" title="关于质数：（难度级别：⭐⭐⭐）"></a>关于质数：（难度级别：⭐⭐⭐）</h2><p>级别1：解题代码2022-07-02 23:30已解锁</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> step2;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FindZhiShu</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">/**********begin**********/</span></span><br><span class="line"><span class="comment">//由于偶数中只有2是质数，此处直接将2的值进行输出，如下代码中查找质数时，只需考虑奇数即可</span></span><br><span class="line">        System.out.print(<span class="number">2</span>+<span class="string">&quot; &quot;</span>);</span><br><span class="line">        <span class="comment">//定义标签</span></span><br><span class="line">        OUT:</span><br><span class="line">        <span class="comment">//1不是质数，2是质数但是已经打印输出，因此循环中i的值从3开始即可，i+=2是因为在循环中我们不再考虑偶数</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">3</span>; i &lt;= <span class="number">1000</span>; i+=<span class="number">2</span>) &#123;</span><br><span class="line">        <span class="comment">//请补充程序判断i是否是质数并打印i，如果是质数按照 System.out.print(i+&quot; &quot;); 格式进行打印 </span></span><br><span class="line">            <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">j</span> <span class="operator">=</span> <span class="number">2</span>; j &lt; i; j++) &#123;</span><br><span class="line">                <span class="keyword">if</span>(i % j == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">//如果i对j求余数等于0说明i不是质数</span></span><br><span class="line">                    <span class="keyword">continue</span> OUT;</span><br><span class="line">               &#125;  </span><br><span class="line">           &#125;            </span><br><span class="line">            <span class="comment">//说明i是质数 </span></span><br><span class="line">           System.out.print(i+<span class="string">&quot; &quot;</span>); </span><br><span class="line">       &#125; </span><br><span class="line">        <span class="comment">/**********end**********/</span> </span><br><span class="line">    &#125;  </span><br></pre></td></tr></table></figure><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> step2;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FindZhiShu</span> &#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">		   <span class="comment">/*</span></span><br><span class="line"><span class="comment">		     打印输出质数的时候务必按照如下格式：System.out.print(质数+&quot; &quot;)；</span></span><br><span class="line"><span class="comment">		     使用print进行打印同时被打印输出的质数后加上一个空格，</span></span><br><span class="line"><span class="comment">		     以便于与平台提供的结果格式保持一致！</span></span><br><span class="line"><span class="comment">            */</span>   </span><br><span class="line">		   <span class="comment">/**********begin**********/</span></span><br><span class="line">            a:<span class="keyword">for</span>(<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">2</span>;i &lt; <span class="number">1000</span>;i++)&#123;		<span class="comment">//此循环遍历次数较多，若对代码效率有要求，则可进一步改进代码：如下：</span></span><br><span class="line">                <span class="keyword">for</span>(<span class="type">int</span> <span class="variable">j</span> <span class="operator">=</span> <span class="number">2</span>;j&lt;i;j++)</span><br><span class="line">                <span class="keyword">if</span>(i%j==<span class="number">0</span>)&#123;</span><br><span class="line">                    <span class="keyword">continue</span> a;</span><br><span class="line">                &#125;</span><br><span class="line">                System.out.print(i+<span class="string">&quot; &quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">           <span class="comment">/**********end**********/</span>	</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line">		**********************改进之后的代码*********************</span><br><span class="line"><span class="keyword">package</span> step2;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">FindZhiShu</span> &#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">		   <span class="comment">/*</span></span><br><span class="line"><span class="comment">		     打印输出质数的时候务必按照如下格式：System.out.print(质数+&quot; &quot;)；</span></span><br><span class="line"><span class="comment">		     使用print进行打印同时被打印输出的质数后加上一个空格，</span></span><br><span class="line"><span class="comment">		     以便于与平台提供的结果格式保持一致！</span></span><br><span class="line"><span class="comment">            */</span>   </span><br><span class="line">		   <span class="comment">/**********begin**********/</span></span><br><span class="line"></span><br><span class="line">	System.out.print(<span class="string">&quot;2 &quot;</span>);	<span class="comment">//因为2是特殊的质数，又因下面循环会自动跳过偶数，因此先将2打印出来。</span></span><br><span class="line">	        a:<span class="keyword">for</span>(<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">3</span>;i &lt; <span class="number">1000</span>;i+=<span class="number">2</span>)&#123;</span><br><span class="line">	            <span class="keyword">for</span>(<span class="type">int</span> <span class="variable">j</span> <span class="operator">=</span> <span class="number">2</span>;j&lt;i;j++)</span><br><span class="line">	            <span class="keyword">if</span>(i%j==<span class="number">0</span>)&#123;</span><br><span class="line">	                <span class="keyword">continue</span> a;		<span class="comment">//此方法运用了给循环做标记，以此可以对continue和break进行明确的命令指示。</span></span><br><span class="line">	            &#125;</span><br><span class="line">	            System.out.print(i+<span class="string">&quot; &quot;</span>);</span><br><span class="line">	        &#125;</span><br><span class="line">	       <span class="comment">/**********end**********/</span>	</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h2 id="拓展知识：（break与continue）"><a href="#拓展知识：（break与continue）" class="headerlink" title="拓展知识：（break与continue）"></a>拓展知识：（break与continue）</h2><h5 id="break关键字"><a href="#break关键字" class="headerlink" title="break关键字"></a>break关键字</h5><p>先来看一段代码的运行效果，如下：</p><p><img src="https://data.educoder.net/api/attachments/189112" alt="img"></p><p>可以发现只要你一直输入<code>1</code>程序就会不断的提示你输入选项，可是当你输入<code>2</code>的时候程序就会终止，你能根据这个运行结果想到要实现这个效果，需要编写什么代码吗？<br>可能你已经猜到了，需要使用到<code>break</code>关键字，<code>break</code>翻译过来是“打断”的意思，放在<code>Java</code>程序中的作用就是：<strong>结束整个循环过程</strong><br>好了，现在来一起看看刚刚那段效果的源代码吧。</p><p><img src="https://data.educoder.net/api/attachments/189205" alt="img"></p><p>现在你应该基本了解<code>break</code>的用法了，不过我还有个小秘密要告诉你：</p><p><img src="https://data.educoder.net/api/attachments/189207" alt="img"></p><p>如果我们在循环中使用<code>switch</code>语句，那么在<code>switch</code>语句中<code>break</code>就不能结束当前循环了，而只能结束<code>switch</code>语句。</p><h5 id="continue关键字"><a href="#continue关键字" class="headerlink" title="continue关键字"></a>continue关键字</h5><p><code>continue</code>关键字的用途是：<strong>结束一次循环事件，开始下一个循环事件</strong>，也就是忽略该语句之后的语句，执行循环体的下一次循环。<br>例如：</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">int i = 0;  while(i &lt; 4)&#123;  if(i == 2)&#123;  i++;  continue;  &#125;  System.out.println(i);  i++;  &#125;</span><br></pre></td></tr></table></figure><p>输出结果：<br><code>0</code><br><code>1</code><br><code>3</code></p><h5 id="static关键字"><a href="#static关键字" class="headerlink" title="static关键字"></a>static关键字</h5><p>​ 关于静态代码块你只需要记住一句话：在<strong>类被加载的时候</strong>运行且<strong>只运行一次</strong>。</p><p>​ 静态方法不能使用类的非静态变量；</p><p>​ 静态方法可以直接调用静态方法，但是调用普通方法只能通过对象的实例才能调用。</p><h2 id="数组的两种初始化方法："><a href="#数组的两种初始化方法：" class="headerlink" title="数组的两种初始化方法："></a>数组的两种初始化方法：</h2><h4 id="1-静态初始化"><a href="#1-静态初始化" class="headerlink" title="1.静态初始化"></a>1.静态初始化</h4><p><strong>在程序运行前就能确定数组的大小和数组中的初始数据</strong>我们称之为静态初始化。<br>例如：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">float</span>[] stuScores = &#123;<span class="number">80.0f</span>,<span class="number">70.0f</span>,<span class="number">90.0f</span>,<span class="number">66.5f</span>&#125;;  <span class="type">int</span>[] nums = &#123;<span class="number">80</span>,<span class="number">70</span>, <span class="number">90</span>,<span class="number">66</span>&#125;;  <span class="type">char</span>[] chs = &#123;‘a’,’b’, ‘c’,’d’&#125;;  </span><br></pre></td></tr></table></figure><h4 id="2-动态初始化"><a href="#2-动态初始化" class="headerlink" title="2.动态初始化"></a>2.动态初始化</h4><p><strong>数组的大小或数组中数据在程序运行时才能决定</strong>，且用到<code>new</code>这个关键字来确定数组的大小或初始数据我们称之为动态初始化。<br>定义数组：<code>变量类型[] 数组名 = new 数据类型 [ 数组长度 ];</code></p><p><img src="https://data.educoder.net/api/attachments/189931" alt="img"></p><p>定义数组与初始化分离：</p><p><img src="https://data.educoder.net/api/attachments/189927" alt="img"></p><p>赋值：<br>初始化之后就可以向数组中放数据了，数组中元素都是通过下标来访问的，例如向 <code>stuScores</code>数组中存放学生成绩：</p><p><img src="https://data.educoder.net/api/attachments/189928" alt="img"></p><h4 id="动态创建数组并循环赋值："><a href="#动态创建数组并循环赋值：" class="headerlink" title="动态创建数组并循环赋值："></a>动态创建数组并循环赋值：</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span>[] arr = <span class="keyword">new</span> <span class="title class_">int</span>[sc.nextInt()];</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span> ; i&lt; arr.length ; i++)&#123;</span><br><span class="line"></span><br><span class="line">   arr[i] = sc.nextInt();</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h2 id="数组基础"><a href="#数组基础" class="headerlink" title="数组基础"></a>数组基础</h2><h4 id="如何获取数组的长度："><a href="#如何获取数组的长度：" class="headerlink" title="如何获取数组的长度："></a>如何获取数组的长度：</h4><p>数组的<code>length</code>属性用于记录数组中有多少个元素或存储单元，即记录数组的长度是多少。</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">int[] nums = new int[10];//声明一个int型数组并动态初始化其大小为10</span><br><span class="line">System.out.println(nums.length);//显示当前数组的大小  </span><br></pre></td></tr></table></figure><p>输出：<code>10</code></p><h4 id="一维数组的遍历"><a href="#一维数组的遍历" class="headerlink" title="一维数组的遍历:"></a>一维数组的遍历:</h4><p>通俗的理解，遍历数组就是：<strong>把数组中的元素都看一遍</strong>。</p><p>示例如下：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span>[] arr = &#123;<span class="number">1</span>,<span class="number">3</span>,<span class="number">5</span>,<span class="number">7</span>,<span class="number">9</span>&#125;;  </span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span> ; i&lt;arr.length; i++)&#123;</span><br><span class="line">	System.out.print(arr[i] + <span class="string">&quot;,&quot;</span>);  </span><br><span class="line">&#125;  </span><br><span class="line"><span class="comment">//输出：`1,3,5,7,9`</span></span><br></pre></td></tr></table></figure><h4 id="二维数组的遍历："><a href="#二维数组的遍历：" class="headerlink" title="二维数组的遍历："></a>二维数组的遍历：</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">for(int i =0;i&lt;scores.length;i++)&#123;</span><br><span class="line">            for(int j=0;j&lt;scores[i].length;j++)		//此处要加上遍历的行数，，即j&lt;scores[i].length</span><br><span class="line">            System.out.println(scores[i][j]);</span><br><span class="line">            System.out.println();</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure><h4 id="如何获取数组的最大值："><a href="#如何获取数组的最大值：" class="headerlink" title="如何获取数组的最大值："></a>如何获取数组的最大值：</h4><p>要求出数组的最大值，是不是很像是打擂台呢？</p><p><img src="https://data.educoder.net/api/attachments/193188" alt="img"></p><p>对于一群人我们不知道谁最厉害，所以我们准备一个擂台，并挑选第一个人为擂主（max），擂台下的人不断的（循环）来挑战擂主。</p><h4 id="数据类型强制转换："><a href="#数据类型强制转换：" class="headerlink" title="数据类型强制转换："></a>数据类型强制转换：</h4><p>测试输入：<code>5</code>，<code>1</code>，<code>151</code>，<code>12</code>，<code>22</code>，<code>100</code>； 预期输出：<br><code>平均值：57.2</code><br><code>最大值：151</code></p><p>提示：</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">int a = 3;  int b = 2;  System.out.println(a/b);  System.out.println((double)a/b);  </span><br></pre></td></tr></table></figure><p>输出：<br><code>1</code><br><code>1.5</code></p><p>例题如下：</p><h4 id="编程要求"><a href="#编程要求" class="headerlink" title="编程要求"></a>编程要求</h4><p>根据提示，在右侧编辑器<code>Begin-End</code>处补充代码，计算并输出数组的平均值和最大值。</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> step3;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Scanner;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">HelloWorld</span> &#123;</span><br><span class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">		<span class="type">Scanner</span> <span class="variable">sc</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Scanner</span>(System.in);</span><br><span class="line">		</span><br><span class="line">		<span class="type">int</span>[] scores = <span class="keyword">new</span> <span class="title class_">int</span>[sc.nextInt()];</span><br><span class="line">		</span><br><span class="line">		<span class="comment">//循环给数组赋值</span></span><br><span class="line">		<span class="keyword">for</span>(<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span> ; i&lt; scores.length;i++)&#123;</span><br><span class="line">			scores[i] = sc.nextInt();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="comment">/********** Begin **********/</span></span><br><span class="line">		<span class="comment">//在这里计算数组scores的平均值和最大值</span></span><br><span class="line">		<span class="type">int</span> sum=<span class="number">0</span>,max=<span class="number">0</span>;</span><br><span class="line">        <span class="type">double</span> av=<span class="number">0</span>;<span class="comment">//此处是因为提前声明了一个double变量，否则则需要强制类型转换。</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">0</span>;i&lt;scores.length;i++)&#123;</span><br><span class="line">            sum+=scores[i];</span><br><span class="line">        &#125;</span><br><span class="line">        av=sum/scores.length;</span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> i=<span class="number">0</span>;i&lt;scores.length;i++)&#123;</span><br><span class="line">            <span class="keyword">if</span>(max&lt;scores[i])&#123;</span><br><span class="line">                max=scores[i];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">		System.out.println(<span class="string">&quot;平均值：&quot;</span> +av ); </span><br><span class="line">        <span class="comment">//若不声明多变量，则用这句强制转换类型。</span></span><br><span class="line">        <span class="comment">//System.out.println(&quot;平均值：&quot; +(double)sum/scores.length );</span></span><br><span class="line">		System.out.println(<span class="string">&quot;最大值：&quot;</span> +max );</span><br><span class="line">		<span class="comment">/********** End **********/</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure><h4 id="获取二维数组的行列长度："><a href="#获取二维数组的行列长度：" class="headerlink" title="获取二维数组的行列长度："></a>获取二维数组的行列长度：</h4><p>二维数组定义：<code>int array[][] = new int[3][3];</code><br>获取行数： <code>int rowLength = array.length;</code><br>获取列数： <code>int colLength = array[0].length;</code></p><h4 id="二维数组的遍历"><a href="#二维数组的遍历" class="headerlink" title="二维数组的遍历"></a>二维数组的遍历</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Test</span>&#123;</span><br><span class="line">	<span class="keyword">for</span>(<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; array.length; i++)&#123;</span><br><span class="line">		<span class="keyword">for</span>(<span class="type">int</span> <span class="variable">j</span> <span class="operator">=</span> <span class="number">0</span>; j &lt; array[i].length; j++)&#123;		<span class="comment">//此处要加上遍历的行数，，即j&lt;scores[i].length</span></span><br><span class="line">			System.out.println(array[i][j);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="知识拓展"><a href="#知识拓展" class="headerlink" title="知识拓展"></a><em>知识拓展</em></h4><p><strong>for-each</strong></p><p>for-each 循环通常用于遍历数组和集合，它的使用规则比普通的 for 循环还要简单，不需要初始变量，不需要条件，不需要下标来自增或者自减。来看一下语法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(元素类型 元素 : 数组或集合)&#123;  </span><br><span class="line"><span class="comment">// 要执行的代码</span></span><br><span class="line">&#125;  </span><br></pre></td></tr></table></figure><p>来看一下示例：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ForEachExample</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        String[] strs = &#123;<span class="string">&quot;沉默王二&quot;</span>, <span class="string">&quot;一枚有趣的程序员&quot;</span>&#125;;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (String str : strs) &#123;</span><br><span class="line">            System.out.println(str);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>输出：</p><figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">沉默王二</span><br><span class="line">一枚有趣的程序员</span><br></pre></td></tr></table></figure><h4 id="两数交换"><a href="#两数交换" class="headerlink" title="两数交换:"></a>两数交换:</h4><p>两个变量数值的交换有三种换发：</p><p>（1）借助中间量交换 （开发常用）</p><p>理解：三个杯子，两杯装水，其中一个空杯子用作容器。</p><p>int x = 10;<br>int y = 20;<br>int z = x;<br>x = y;<br>y = z;<br>　（2）位移运算交换 （面试常用）</p><p>理解：涉及到了异或运算符的规则：一个数对另一个数位异或两次，该数不变</p><p>int x = 10;<br>int y = 20;<br>x = x ^ y;<br>y = x ^ y;<br>x = x ^ y;<br>　（3）数值相加减交换</p><p>理解：先求得两数的和再进行减运算</p><p>int x = 10;<br>int y = 20;<br>x = x + y;<br>y = x - y;<br>x = x - y;</p><h2 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h2><h4 id="选择排序："><a href="#选择排序：" class="headerlink" title="选择排序："></a>选择排序：</h4><h5 id="实现过程"><a href="#实现过程" class="headerlink" title="实现过程"></a>实现过程</h5><p>为了实现选择排序，我们需要<strong>求出最大值</strong>，并且和相比较的数据<strong>交换位置</strong>：接下来我们对数组<code>int[] arr = &#123;6,5,8,0,2,9&#125;</code>来进行<strong>第一趟循环</strong>，将最大值移动到数组的第一位。</p><p><img src="https://data.educoder.net/api/attachments/191743" alt="img"></p><p>代码实现：</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">int[] arr = &#123;6,5,8,0,2,9&#125;;for (int i = 0; i &lt; arr.length-1; i++) &#123;      if(arr[0] &lt; arr[i+1])&#123;          int temp = arr[0];          arr[0] = arr[i+1];          arr[i+1] = temp;      &#125;  &#125;  </span><br></pre></td></tr></table></figure><p>一次循环操作就可以找出数组中的最大值，并将其移动到数组的首位，所以对于一个长度为<code>6</code>的数组，我们只需要进行<code>5</code>（length-1）次上述操作即可将数组降序排序了。</p><p>接下来我们进行<strong>第二趟循环</strong>，求第二大的值，并将其移动到数组的第二个位置。因为我们已经求出了最大值，所以这一次循环，最大值不用参与比较。</p><p><img src="https://data.educoder.net/api/attachments/191767" alt="img"></p><p>代码实现：</p><p><img src="https://data.educoder.net/api/attachments/191770" alt="img"></p><p>结果：<code>[9, 8, 5, 0, 2, 6]</code></p><p>可以发现经过两轮循环我们找出了数组中最大的两个值，并且移动他们到了数组的前两位。</p><p>现在按照上述步骤就可以实现数组的排序了，不过如果我们照搬上述代码，就会有很多冗余的代码，所以需要你来改进，怎么改进是需要你思考的。</p><p><strong>告诉你一个秘密</strong>：使用<code>Arrays.toString(数组)</code>可以直接输出数组中的值哦！<br>如下：</p><p><img src="https://data.educoder.net/api/attachments/191773" alt="img"></p><p>输出结果：<code>[6, 5, 8, 0, 2, 9]</code></p><p><strong>思考题</strong>：</p><p>本关所讲述的选择排序是一个简化版本，如果你想要学习优化版可以根据下列图片，编写出相应代码，然后在评论区贴出来哦。</p><p><img src="https://data.educoder.net/api/attachments/192416" alt=" "></p><p>上图就是一个使用选择排序将一个数组中数据从小到大排序的过程，请思考如何用代码实现上述过程。</p><p>原理：每一次从待排序的数据元素中选出最小的一个元素，存放在序列的起始位置，直到全部待排序的数据元素排完。</p><hr><p>本关难度较大，但这是学习数组绕不过去的一关，多思考，多尝试，你能成功的，加油！</p></article><div class="mt-12 pt-6 border-t border-gray-200"><span class="bg-gray-100 dark:bg-gray-700 px-2 py-1 m-1 text-sm rounded-md transition-colors hover:bg-gray-200"><a href="/tags/educoder/">educoder</a></span></div><div class="flex justify-between mt-12 pt-6 border-t border-gray-200"><div><a href="/posts/ebc19133.html" class="text-sm text-gray-400 hover:text-gray-500 flex justify-center"><iconify-icon width="20" icon="ri:arrow-left-s-line" data-inline="false"></iconify-icon>最常用的Git命令汇总</a></div><div><a href="/posts/94c52c92.html" class="text-sm text-gray-400 hover:text-gray-500 flex justify-center">Linux 常用命令积累<iconify-icon width="20" icon="ri:arrow-right-s-line" data-inline="false"></iconify-icon></a></div></div><div class="article-comments mt-12"><div class="giscus-container mt-8 pt-8 border-t border-gray-200 dark:border-gray-700"><script src="https://giscus.app/client.js" data-repo="WL2O2O/CS_GUIDER_Giscus" data-repo-id="R_kgDOJYdTQw" data-category="Announcements" data-category-id="DIC_kwDOJYdTQ84CWKC6" data-mapping="pathname" data-strict="0" data-reactions-enabled="1" data-emit-metadata="0" data-input-position="top" data-theme="preferred_color_scheme" data-lang="en" crossorigin="anonymous" async></script></div><script>function updateGiscusTheme(){const e=document.querySelector("iframe.giscus-frame");if(e){const s=document.documentElement.classList.contains("dark");e.contentWindow.postMessage({giscus:{setConfig:{theme:s?"dark":"light"}}},"https://giscus.app")}}window.addEventListener("message",e=>{"https://giscus.app"===e.origin&&e.data.giscus&&e.data.giscus.resizeHeight&&updateGiscusTheme()});const observer=new MutationObserver(()=>{updateGiscusTheme()});observer.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]})</script></div></section><script src="/lib/clipboard.min.js"></script><script async src="https://cdn.jsdelivr.net/npm/mathjax@2/MathJax.js?config=TeX-MML-AM_CHTML"></script><script type="text/x-mathjax-config">MathJax.Hub.Config({
    "HTML-CSS": {
        preferredFont: "TeX",
        availableFonts: ["STIX","TeX"],
        linebreaks: { automatic:true },
        EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
        inlineMath: [ ["$", "$"], ["\\(","\\)"] ],
        processEscapes: true,
        ignoreClass: "tex2jax_ignore|dno",
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
        equationNumbers: { autoNumber: "AMS" },
        noUndefined: { attributes: { mathcolor: "red", mathbackground: "#FFEEEE", mathsize: "90%" } },
        Macros: { href: "{}" }
    },
    messageStyle: "none"
  });</script><script type="text/x-mathjax-config">MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });</script><script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script><script>$(document).ready(()=>{mermaid.initialize({theme:"default",logLevel:3,flowchart:{curve:"linear"},gantt:{axisFormat:"%m/%d/%Y"},sequence:{actorMargin:50}})})</script><script src="/lib/fancybox/fancybox.umd.min.js"></script><script>$(document).ready(()=>{$(".post-content").each((function(a){$(this).find("img").each((function(){if(!$(this).parent().hasClass("fancybox")&&!$(this).parent().is("a")){var a=this.alt;a&&$(this).after('<span class="fancybox-alt">'+a+"</span>"),$(this).wrap('<a class="fancybox-img" href="'+this.src+'" data-fancybox="gallery" data-caption="'+a+'"></a>')}})),$(this).find(".fancybox").each((function(){$(this).attr("rel","article"+a)}))})),Fancybox.bind('[data-fancybox="gallery"]',{})})</script><script src="/lib/tocbot/tocbot.min.js"></script><script>$(document).ready(()=>{tocbot.init({tocSelector:".post-toc",contentSelector:".post-content",headingSelector:"h1, h2, h3",hasInnerContainers:!0})})</script></main><footer class="flex flex-col h-40 items-center justify-center text-gray-400 text-sm"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div class="flex items-center gap-2"><span>Visitors</span> <span id="busuanzi_value_site_uv"></span> <span>Page Views</span> <span id="busuanzi_value_site_pv"></span></div><div class="flex items-center gap-2"><a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/" style="color:inherit">CC BY-NC-SA 4.0</a> <span>© 2025</span><iconify-icon width="18" icon="emojione-monotone:desktop-computer"></iconify-icon><a href="https://github.com/wl2o2o" target="_blank" rel="noopener noreferrer">CS_GUIDER</a></div><div class="flex items-center gap-2"><span>Powered by</span> <a href="https://hexo.io/" target="_blank" rel="noopener noreferrer">Hexo</a> <span>&</span> <a href="https://github.com/wl2o2o" target="_blank" rel="noopener noreferrer">CS_GUIDER</a></div></footer><div class="back-to-top box-border fixed right-6 z-1024 -bottom-20 rounded py-1 px-1 bg-slate-900 opacity-60 text-white cursor-pointer text-center dark:bg-slate-600"><span class="flex justify-center items-center text-sm"><iconify-icon width="18" icon="ion:arrow-up-c" id="go-top"></iconify-icon><span id="scrollpercent"><span>0</span> %</span></span></div><script src="/js/main.js"></script><script src="/js/search.js"></script><script>$(document).ready((function(){const t=document.getElementById("maple");Array.from({length:"10"}).map(()=>{const e=document.createElement("div"),a=.5*Math.random()+.5,l=2*Math.random()-1,n=Math.random()*t.clientWidth,i=-Math.random()*t.clientHeight;return e.className="maple",e.style.width=24*a+"px",e.style.height=24*a+"px",e.style.left=n+"px",e.style.top=i+"px",e.style.setProperty("--maple-fall-offset",l),e.style.setProperty("--maple-fall-height",Math.abs(i)+t.clientHeight+"px"),e.style.animation=`fall ${10/"0.3"}s linear infinite`,e.style.animationDelay=-10/"0.3"+"s",t.appendChild(e),e})}))</script><div class="fixed top-0 bottom-0 left-0 right-0 pointer-events-none print:hidden" id="maple"></div></body></html>